package eatpoopyoucat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.*;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;

public class NewGameServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(NewGameServlet.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        String content = req.getParameter("content");
        String userListString = req.getParameter("userList");
        
        List<User> userList = new ArrayList<User>();
        String[] listItems = userListString.split(";");
        Pattern emailRegex = Pattern.compile("^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$", Pattern.CASE_INSENSITIVE);
        // There should be something to catch this and stop it...
        if (listItems.length <= 1) throw new RuntimeException( "Not enough players" );
        for (int i = 0; i < listItems.length; i++) {
        	try {
				Matcher m = emailRegex.matcher(listItems[i]);
				if (!m.matches()) throw new RuntimeException( "Not a valid email address" );
				else {
					User tmpUser = new User(listItems[i], "gmail.com");
					userList.add(tmpUser);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

        // I bet there's a better way to do this...
        Date date = new Date();
        EpycGame game = new EpycGame(userList, date, null);
        EpycMessage message = new EpycMessage(content, null);
      	
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	// This must be wrong. There's no way I have to keep making these things persistent...
            pm.makePersistent(game);
            message.setGameID(game.getKey());
            pm.makePersistent(message);
            game.setLastContentID(message.getKey());
            pm.makePersistent(message);
        } finally {
            pm.close();
        }

        resp.sendRedirect("/epyc.jsp");
    }

}
